<script lang="ts" setup>
import "swiper/swiper-bundle.css";
import { reactive, ref, onActivated } from "vue";
import { HomeAxios } from "@/api/home.ts";
import { UserStore } from "@/store";
import { showLoadingToast, closeToast, showSuccessToast } from "vant";
import { Swiper, SwiperSlide } from "swiper/vue";
import SwiperTemp, { Pagination, Navigation } from "swiper";
import sortBy from "lodash";
//import loadImg from "@/image/new_img/load.gif";
// import Pubsub from "pubsub-js";
// import { PubSubEnum } from "@/types";
import { useRouter } from "vue-router";
import { RouterEnums } from "@/types";
import { FiltrationFun, groupLogolist } from "@/utils";
import { useI18n } from "vue-i18n";
import { judgeLang } from "@/utils";
const router = useRouter();
SwiperTemp.use([Pagination]);
const modules = reactive([Navigation]);
const refSwiper = ref(null);
const userStore = UserStore();
const { locale, t } = useI18n(); // 获取当前语言
/********************新的************************** */

onActivated(() => {
  getGroupClusters();
});
const gameOperatorsList: any = ref([]);
//获取分组的
const getGroupClusters = () => {
  // HomeAxios.getGroupClusters().then(res => {
  //   // res.list.sort((a, b) => a.id - b.id);
  //   gameOperatorsList.value = res.list.filter(item => item.state === 0);
  //   res.list.map(async (item: any) => {
  //     item.customLogo = groupLogolist(item.groupName, "");
  //     item.defaultIcon = item.customLogo;
  //     if (item.state === 0) {
  //       if (item.groupType === 0) {
  //         //游戏列表
  //         await getGameList(item.id, item.customLogo, item.showNumber);
  //       }
  //     }
  //   });
  //   emits("getGameData", res.list);
  // });
  HomeAxios.getGameListAll({ pageNo: 1, pageSize: 100 }).then((res: any) => {
    const companyList: any = [];
    // gameOperatorsList.value = res.list.filter(item => item.state === 0);
    gameOperatorsList.value = res.list;
    const collectList: any = []; //收藏的
    res.list.map(async (item: any) => {
      item.customLogo = groupLogolist(item.groupName, "");
      item.defaultIcon = item.customLogo;
      const setData = {
        customLogo: item.customLogo,
        defaultIcon: item.defaultIcon,
        groupId: item.groupId,
        groupName: item.groupName,
        groupType: item.groupType,
      };
      item.gameList.map(dataRes => {
        if (dataRes.isCollect === "1") {
          dataRes.collectShow = true;
          collectList.push(dataRes);
        } else {
          dataRes.collectShow = false;
        }
      });
      companyList.push(setData);
    });
    if (collectList.length > 0) {
      localStorage.setItem(
        "collectIds" + userStore.userLoginInfo.account.uid,
        JSON.stringify(collectList),
      );
    } else {
      localStorage.removeItem("collectIds" + userStore.userLoginInfo.account.uid);
    }
    res.list.map(item => {
      item.providerLogo = groupLogolist(item.groupName, "");
      // getlist(item.gameList);
    });
    res.list.map(item => {
      item.gameList = chunkArray(item.gameList, item.showNumber);
    });

    // gameList.list.push(res);
    gameList.list = res.list;
    emits("getGameData", companyList);
  });
};
//游戏列表
const gameList: any = reactive({ list: [] });
const getGameList = async (id, customLogo, showNumber) => {
  const data = {
    groupId: id,
    pageNo: 1,
    pageSize: 1000000,
  };
  await HomeAxios.gameList(data).then((res: any) => {
    if (res) {
      res.providerLogo = customLogo;
      res.groupId = id;
      //获取收藏列表
      const collectlist = localStorage.getItem("collectIds" + userStore.userLoginInfo.account.uid);
      gameCollectList.list =
        collectlist !== null && collectlist !== "" ? JSON.parse(collectlist) : [];
      res.list = chunkArray(res.list, showNumber);
      gameList.list.push(res);
      gameList.list.map(item => {
        getlist(item.list);
      });
      // gameList.list.sort((a, b) => a.groupId - b.groupId);
      const idOrder = gameOperatorsList.value.map(item => item.id);
      gameList.list.sort((a, b) => {
        const indexA = idOrder.indexOf(a.groupId);
        const indexB = idOrder.indexOf(b.groupId);
        return indexA - indexB; // 按照 id 顺序排序
      });
    }
  });
};
//刷新收藏的列表
const refreshCollectionType = () => {
  const collectlist = localStorage.getItem("collectIds" + userStore.userLoginInfo.account.uid);
  gameCollectList.list = collectlist !== null && collectlist !== "" ? JSON.parse(collectlist) : [];
  // gameList.list.map(item => {
  //   getlist(item.list);
  // });
  setCollectList(gameList.list);
};
const setCollectList = arr => {
  for (const key in arr) {
    // arr[key].list.forEach(sublist => {
    //   sublist.forEach(item => {
    //     // 根据 gameId 和 providerId 查找是否在 gameCollectList.list 中
    //     const match = gameCollectList.list.some(
    //       collect => collect.gameId === item.gameId && collect.providerId === item.providerId,
    //     );

    //     // 如果匹配，将 collectShow 设置为 true，否则为 false
    //     item.collectShow = match;
    //   });
    // });
    arr[key].gameList.forEach(sublist => {
      sublist.forEach(item => {
        // 根据 gameId 和 providerId 查找是否在 gameCollectList.list 中
        const match = gameCollectList.list.some(
          collect => collect.gameId === item.gameId && collect.providerId === item.providerId,
        );

        // 如果匹配，将 collectShow 设置为 true，否则为 false
        item.collectShow = match;
      });
    });
  }
};
/*********分组******************* */
const arr: any = reactive({ list: [] });
const getlist = list => {
  //添加收藏字段列表
  const collectGameList: any = [];
  for (let listitem of list) {
    if (listitem) {
      if (gameCollectList.list.length > 0 && userStore.isLogin) {
        for (let z = 0; z < listitem.length; z++) {
          for (let i = 0; i < gameCollectList.list.length; i++) {
            let collectdata = gameCollectList.list[i];

            if (
              listitem[z].gameId === collectdata.gameId &&
              listitem[z].providerId === collectdata.providerId
            ) {
              listitem[z].collectShow = true;
            } else {
              if (!listitem[z].collectShow) {
                listitem[z].collectShow = false;
              }
              // listitem[z].collectShow = listitem.collectShow ? true : false;
            }
            if (listitem.collectShow) {
              collectGameList.push(listitem);
            }
          }
        }
      } else {
        if (listitem) {
          listitem.collectShow = false;
        }
      }
    }
  }
};

/******************************旧的***************************** */
const gameCollectList: any = reactive({ list: [] });
//点击打开游戏链接
const getGemoUrl = sortBy.throttle(data => {
  if (userStore.isLogin) {
    // if (userStore.balance === 0) {
    //   Pubsub.publish(PubSubEnum.SHOW_ERROR_TIP, {
    //     text: "请先充值",
    //   });
    //   return false;
    // }
    showLoadingToast({
      message: "loading...",
      forbidClick: true,
    });
    const item = {
      providerId: data.providerId,
      gameId: data.gameId,
      Lang: judgeLang(locale.value),
    };
    //获取游戏链接1
    HomeAxios.getGameUrl(item).then(res => {
      if (res.url) {
        // getGameUrlData = res
        //获取根据运营商id游戏专属tokne
        HomeAxios.getGameToken({
          providerId: data.providerId,
          op: 1,
        }).then(msg => {
          //根据游戏商运行的ID和token充值2
          HomeAxios.gameRecharge({
            providerId: data.providerId,
            money: "",
            token: msg.token,
          }).then(() => {
            closeToast();
            // window.location.href = res.url;
            emits("openGameUrl", res.url);
            FiltrationFun.setReportEvent("StartTrial");
          });
        });
      }
    });
  } else {
    router.push(RouterEnums.LOGIN);
  }
}, 1500);
const emits = defineEmits(["openGameUrl", "getGameData", "openGamePageList"]);

// 1. 根据 providerId 分组
// function groupByProvider(games) {
//   return games.reduce((acc, game) => {
//     const { providerId } = game;
//     if (!acc[providerId]) acc[providerId] = [];
//     acc[providerId].push(game);
//     return acc;
//   }, {});
// }

// 2. 在每个分组内部排序
// function sortGames(games) {
//   return games.sort((a, b) => {
//     if (a.collectShow !== b.collectShow) {
//       return a.collectShow ? -1 : 1; // collectShow 为 true 的排在前
//     }
//     return a.gameId - b.gameId; // 再按 gameId 从小到大排序
//   });
// }

// 3. 将数组按长度 size数量 切割
function chunkArray(array, size) {
  const result: any = [];
  for (let i = 0; i < array.length; i += size) {
    result.push(array.slice(i, i + size));
  }
  return result;
}
// interface updateUserInfo {
//   collectShow: boolean;
//   demoInstanceId: string;
//   gameId: number;
//   gameLogo: string;
//   gameName: string;
//   gameType: number;
//   gameUrl: string;
//   instantId: string;
//   providerId: number;
// }
// 4. 分组、排序并组织成指定结构
// function processGames(games) {
//   const grouped = groupByProvider(games);
//   return Object.entries(grouped).map(([providerId, gameList]) => ({
//     providerId: Number(providerId),
//     gamelist: chunkArray(sortGames(gameList), 9),
//     total: (gameList as updateUserInfo[]).length,
//   }));
// }

//点击收藏游戏
const collectGame = sortBy.throttle((indexs, indexlist, gameindex, item) => {
  if (!userStore.isLogin) {
    router.push(RouterEnums.LOGIN);
    return false;
  }
  const collectIdlist = localStorage.getItem("collectIds" + userStore.userLoginInfo.account.uid);
  const list = collectIdlist !== null && collectIdlist !== "" ? JSON.parse(collectIdlist) : [];
  if (list.length > 0) {
    const index = list.findIndex(
      listitem => listitem.gameId === item.gameId && listitem.providerId === item.providerId,
    );
    if (index !== -1) {
      // 存在匹配对象，删除它，collectType：1-收藏 2-取消收藏
      list.splice(index, 1);
      gameList.list[indexs].gameList[indexlist][gameindex].collectShow = false;
      HomeAxios.clickCollect({ collectType: "2", gameId: item.gameId }).then(() => {
        showSuccessToast(t("home.cancelamento"));
      });
    } else {
      // 不存在匹配对象，添加它 collectType：1-收藏 2-取消收藏
      gameList.list[indexs].gameList[indexlist][gameindex].collectShow = true;
      list.push(item);
      HomeAxios.clickCollect({ collectType: "1", gameId: item.gameId }).then(() => {
        showSuccessToast(t("home.favoritos"));
      });
    }
  } else {
    //没有就收藏 1-收藏 2-取消收藏
    list.push(item);
    gameList.list[indexs].gameList[indexlist][gameindex].collectShow = true;
    HomeAxios.clickCollect({ collectType: "1", gameId: item.gameId }).then(() => {
      showSuccessToast(t("home.favoritos"));
    });
  }
  const gameListString = list.length > 0 ? JSON.stringify(list) : "";
  localStorage.setItem("collectIds" + userStore.userLoginInfo.account.uid, gameListString);
}, 1000);
//跳转游戏页面
const openGamePageList = (groupId, _item) => {
  emits("openGamePageList", groupId);
};
defineExpose({ arr, getGameList, getGroupClusters, refreshCollectionType });
</script>
<template>
  <div class="game-frame">
    <!-- 游戏模块 -->
    <div v-for="(item, index) in gameList.list" :key="index" class="game-content-frame">
      <div class="game-top-frame df ai-center jc-space-between">
        <img class="firm-logo" :title="item.groupId" :src="item.providerLogo" />
        <div class="select-game-frame df ai-center">
          <img
            class="select-button leftimg swiper-prev"
            :class="`swiper-prev-${index}`"
            style="display: block"
            src="@/image/new_img/home/homev2_gamearrow_right.png"
          />
          <div class="game-number" @click="openGamePageList(item.groupId, item)">
            {{ item.total }}
          </div>
          <img
            class="select-button swiper-next"
            :class="`swiper-next-${index}`"
            style="display: block"
            src="@/image/new_img/home/homev2_gamearrow_right.png"
          />
          <img
            class="select-more-button"
            src="@/image/new_img/home/homev2_game_more.png"
            @click="openGamePageList(item.groupId, item)"
          />
        </div>
      </div>
      <div class="gameList-frame">
        <div class="gameImgframe">
          <Swiper
            ref="refSwiper"
            class="swiper"
            :modules="modules"
            :navigation="{
              nextEl: `.swiper-next-${index}`,
              prevEl: `.swiper-prev-${index}`,
            }"
            :slides-per-view="1"
            :pagination="false"
          >
            <!-- <SwiperSlide v-for="(items, indexs) in item.list" :key="indexs"> -->
            <SwiperSlide v-for="(items, indexs) in item.gameList" :key="indexs">
              <!-- df fw-wrap -->
              <div class="sangebuiju-frame" style="width: 100%; height: auto; margin-left: 2px">
                <div
                  v-for="(itemImg, indexImg) in items"
                  :key="indexImg"
                  class="img-frame"
                  :imgUrl="itemImg.gameLogo"
                  @click="getGemoUrl(itemImg)"
                >
                  <img :id="itemImg.gameId" class="game-img-style" :src="itemImg.gameLogo" />
                  <div
                    class="collect-img-frame"
                    @click.stop="collectGame(index, indexs, indexImg, itemImg)"
                  >
                    <div class="collect-img-content">
                      <img
                        v-show="itemImg.collectShow"
                        class="collect-img"
                        src="@/image/new_img/home/bofang_caise.png"
                      />
                      <img
                        v-show="!itemImg.collectShow"
                        class="collect-img"
                        src="@/image/new_img/home/shoucang_bai.png"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </SwiperSlide>
          </Swiper>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="less" scoped>
.sangebuiju-frame {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr; /* 每列的宽度相等 */
  grid-gap: 10px; /* 格子之间的间隙 */
  /* 如果你想要不同的列宽，可以这样设置：
     grid-template-columns: 1fr 2fr 1fr; */
}
.game-frame {
  width: 100%;
  height: auto;
  margin-top: 20px;
}

.game-content-frame {
  width: 100%;
  height: auto;
  margin-bottom: 60px;
}

.game-top-frame {
  width: calc(100 - 27px);
  height: 62.875px;
  background-image: url("../../image/new_img/home/homev2_game_groupbg.png");
  background-size: 100% 100%;
  object-fit: cover;
  margin-left: 27px;
}

.firm-logo {
  width: auto;
  height: 66px;
}

.select-button {
  width: 45px;
  height: 50px;
}

.select-game-frame {
  margin-right: 27px;
}

.leftimg {
  transform: rotate(180deg);
}

.game-number {
  width: 84px;
  height: 49.45px;
  font-size: 24px;
  color: rgba(255, 255, 255, 0.45);
  text-align: center;
  line-height: 49.45px;
  background-image: url("../../image/new_img/home/homev2_game_num.png");
  margin-left: 5px;
  margin-right: 5px;
  background-size: 100% 100%;
  object-fit: cover;
}

.select-more-button {
  width: 75.7031px;
  height: 50px;
  margin-left: 5px;
}

.gameList-frame {
  width: calc(100% - 58px);
  height: auto;
  margin-left: 27px;
  margin-top: 20px;

  .gameImgframe {
    width: 100%;
    height: 100%;
  }

  .img-frame:nth-child(3n + 0) {
    margin-right: 0px;
    width: 98%;
  }

  .img-frame {
    width: 100%;
    height: 280.672px;
    margin-bottom: 14px;
    border-radius: 33.4px;
    overflow: hidden;
    position: relative;
    top: 0;
    left: 0;
    // margin-right: 14px;
    .collect-img-frame {
      width: 40px;
      height: 40px;
      background: rgba(0, 0, 0, 0.65);
      padding: 7px;
      position: absolute;
      right: 12px;
      top: 6px;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      .collect-img-content {
        position: relative;
        left: 0;
        top: 0;
        .collect-img {
          width: 40px;
          height: 40px;
          position: absolute;
          right: 0;
          top: 6;
          border-radius: 50%;
        }
      }
    }
  }

  .game-img-style {
    width: 100%;
    height: 280.672px;
    border-radius: 33.4px;
  }

  .spacing {
    margin-right: 0px;
    margin-bottom: 0px;
  }
}

.my-swipe .van-swipe-item {
  color: #fff;
  font-size: 20px;
  line-height: 150px;
  text-align: center;
  background-color: #39a9ed;
}
</style>
